package com.lihao.walkers.surfaceview;

import java.util.Date;

import com.lihao.walkers.utils.Constants;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.Handler;
import android.os.Message;

/**
 * 方向传感器。
 * @author lihao
 */
public class TrackSensorListener implements SensorEventListener {

	/** 用于发消息的handler。 */
	private Handler mHostHandler = null;

	/** 上次发送消息的时间。 */
	private long mLastSendTime = 0;

	public TrackSensorListener() {
		mHostHandler = SurfaceActivity.getHandler();
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		float degree = event.values[0]; // 获得X方向角度。
		degree = (degree + 720) % 360;
		if(mHostHandler != null){
			long currentTime = new Date().getTime();
			if(Math.abs(currentTime - mLastSendTime) > Constants.UPGRADE_TRACK_PADDING){
				mLastSendTime = currentTime;
				Message msg = mHostHandler.obtainMessage();
				msg.what = Constants.UPGRADE_TARGET_VIEW;
				msg.obj = degree; // 将偏移角度传送过去。
				mHostHandler.sendMessage(msg);
			}
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {

	}
}
